package fisio.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import fisio.connection.ConnectionManager;
import fisio.model.Foto;

public class FotoDAO {
	
	private static final String SQL_GET_FOTO_BY_ID = "SELECT * FROM foto WHERE id_fo = ?";
	private static final String SQL_INSERT_FOTO = "INSERT INTO foto (dado) VALUES (?)";
	
	public static Foto getFoto(int id) {
		if (id == -1)
			return null;
		
		Connection conn = ConnectionManager.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		Foto foto = null;

		try {

			stmt = conn.prepareStatement(SQL_GET_FOTO_BY_ID);
			stmt.setInt(1, id);
			
			rs = stmt.executeQuery();
			if(rs.next()) {
				foto = new Foto(rs.getBinaryStream(2));
				foto.setId(rs.getInt(1));
			}

			rs.close();
			stmt.close();
			conn.close();
			
		} catch(SQLException e) {
			System.out.println();
			System.out.println("ERROR @fisio.dao.FotoDAO.getFoto(int)");
			e.printStackTrace();
		}

		return foto;
	}
	
	public static Foto insertFoto(Foto foto) {

		Connection conn = ConnectionManager.getConnection();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		int id_f = -1;
		
		try {

			stmt = conn.prepareStatement(SQL_INSERT_FOTO, Statement.RETURN_GENERATED_KEYS);
			stmt.setBinaryStream(1, foto.getFoto(), (int)foto.getSize());
			
			stmt.executeUpdate();
			
			rs = stmt.getGeneratedKeys();
			if(rs.next()) {
				id_f = rs.getInt(1);				
			}
			
			rs.close();
			stmt.close();
			conn.close();

		} catch(SQLException e) {
			System.out.println();
			System.out.println("ERROR @fisio.dao.FotoDAO.insertFoto(fisio.model.Foto)");
			e.printStackTrace();
		}
		
		foto.setId(id_f);
		return foto;
	}
}
